#include "types.h"
#include "file.h"
#include "string.h"

int main(){
    uint op;
    int size;
    char cmd[MAXSTRLEN];
    char name[MAXSTRLEN];
    uint32 parentid;
    uint32 inodeid;
    int i;
    initfs();
    while(1){
        memset(cmd, 0, sizeof(cmd));
        memset(name, 0, sizeof(name));
        printf("LoanCold: root$ ");
        gets(cmd);
        size = strlen(cmd);
        
        i=0;
        // clear empty space
        while(i<size && cmd[i]==' ')
            i++;
        if(i>=size)
            goto invalidcmd;
        //op
        while(i<size && cmd[i]!=' ')
            i++;
        cmd[i++] = '\0';
        while(i<size && cmd[i]==' ')
            i++;

        if(!strcmp(cmd,"touch")){
            // touch filename
            inodeid = finditem_path(cmd+i, &parentid, name);
            // printf("touch: parent:%d name:%s\n",parentid , name);
            if(inodeid){
                printf("file already exists\n");
                goto nextcmd;
            }
            touchitem(parentid, name, ITEM_FILE);
        }
        else if(!strcmp(cmd,"mkdir")){
            // mkdir dirname
            inodeid = finditem_path(cmd+i, &parentid, name);
            if(inodeid){
                printf("file already exists\n");
                goto nextcmd;
            }
            touchitem(parentid, name, ITEM_DIR);
        }
        else if(!strcmp(cmd,"cp")){
            uint32 src_inode_id;
            uint32 dst_inode_id;
            int j=i;
            while(j<size && cmd[j]!=' ')
                j++;
            cmd[j++] = '\0';
            // printf("cp arg1:%s arg2:%s\n",cmd+i,cmd+j);
            // i indicates arg1:src
            // j indicates arg2:dst

            src_inode_id = finditem_path_simple(cmd+i);
            if(src_inode_id == 0){
                printf("src file not exists\n");
                goto nextcmd;
            }
            dst_inode_id = finditem_path(cmd+j, &parentid, name);
            if(dst_inode_id != 0){
                printf("target file already exists\n");
                goto nextcmd;
            }
            dst_inode_id = touchitem(parentid, name, ITEM_FILE);
            copyfile(dst_inode_id, src_inode_id);
        }
        else if(!strcmp(cmd,"ls")){
            inodeid = finditem_path_simple(cmd+i);
            printallitem(cmd+i);
        }
        else if(!strcmp(cmd,"shutdown")){
            closefs();
            exit(0);
        }
        else{
invalidcmd:
            printf("Command can't be recognized\n");
        }
        
nextcmd:
        cmd[0] = '\0';
    }
}